package com.yami.shop.platform.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.dto.BlockchainShopDTO;
import com.yami.shop.bean.model.Blockchain;
import com.yami.shop.bean.model.BlockchainShop;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.vo.BlockchainShopVO;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.BlockchainService;
import com.yami.shop.service.BlockchainShopService;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


/**
 * 链平台管理
 *
 * @author lgh
 */
@RestController
@RequestMapping("/platform/blockchain")
@Tag(name = "链平台接口")
public class BlockchainController {

    @Autowired
    private BlockchainService blockchainService;
    @Autowired
    private BlockchainShopService blockchainShopService;
    @Autowired
    private ProductService productService;

    @GetMapping("/page")
    @Operation(summary = "分页获取链平台信息列表", description = "分页获取链平台信息列表")
    public ServerResponseEntity<IPage<Blockchain>> page(PageParam<Blockchain> pageDTO, @ParameterObject Blockchain blockchain) {
        IPage<Blockchain> blockchainIPage = blockchainService.pageCategoryLangList(pageDTO, blockchain);
        return ServerResponseEntity.success(blockchainIPage);
    }

    @GetMapping("/list")
    @Operation(summary = "获取链平台列表（不分页）", description = "获取链平台列表（不分页）")
    public ServerResponseEntity<List<Blockchain>> list(@ParameterObject Blockchain blockchain) {
        List<Blockchain> blockchains = blockchainService.listByParams(blockchain);
        return ServerResponseEntity.success(blockchains);
    }

    @GetMapping("/info/{blockchainId}")
    @Operation(summary = "根据链平台id获取链平台信息", description = "根据链平台id获取链平台信息")
    public ServerResponseEntity<Blockchain> info(@PathVariable("blockchainId") Long blockchainId) {
        // 获取数据库中的链平台，如果链平台为空则抛异常
        Blockchain blockchain = blockchainService.getBlockchainByBlockchainId(blockchainId);
        if (ObjectUtil.isNull(blockchain)) {
            throw new YamiShopBindException("yami.no.auth");
        }
        return ServerResponseEntity.success(blockchain);
    }

    @SysLog("保存链平台")
    @PostMapping
    @Operation(summary = "保存链平台信息", description = "保存链平台信息")
    public ServerResponseEntity<Long> save(@RequestBody Blockchain blockchain) {
        Integer count = blockchainService.getBlockchainName(blockchain);
        if (count > 0) {
            // 类目名称已存在！
            throw new YamiShopBindException("yami.blockchain.name.exist");
        }
        blockchain.setId(null);
        blockchain.setOrderNum(Objects.isNull(blockchain.getOrderNum()) ? 0 : blockchain.getOrderNum());
        blockchainService.saveBlockchain(blockchain);
        return ServerResponseEntity.success(blockchain.getId());
    }

    @SysLog("更新链平台")
    @PutMapping
    @Operation(summary = "更新链平台信息", description = "更新链平台信息")
    public ServerResponseEntity<String> update(@RequestBody Blockchain blockchain) {
        // 获取数据库中的链平台，如果链平台为空则抛异常
        blockchainService.getBlockchainByBlockchainId(blockchain.getId());
        Integer count = blockchainService.getBlockchainName(blockchain);
        if (count > 0) {
            // 类目名称已存在！
            throw new YamiShopBindException("yami.category.name.exist");
        }
        blockchainService.updateBlockchain(blockchain);
        return ServerResponseEntity.success();
    }

    @SysLog("删除链平台")
    @DeleteMapping("/{blockchainId}")
    @Operation(summary = "根据链平台id删除链平台", description = "根据链平台id删除链平台")
    public ServerResponseEntity<String> delete(@PathVariable("blockchainId") Long blockchainId) {
        Blockchain blockchain = blockchainService.getBlockchainByBlockchainId(blockchainId);
        long categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getChain, blockchain.getCode()).ne(Product::getStatus, -1));
        if (categoryProdCount > 0) {
            // 该链平台下还有商品，请先删除该链平台下的商品
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.category.delete.check"));
        }
        blockchainService.deleteBlockchain(blockchain);
        return ServerResponseEntity.success();
    }

    @PutMapping("/updateBrandStatus")
    @Operation(summary = "更新链平台状态（启用或禁用）", description = "更新链平台状态（启用或禁用）")
    public ServerResponseEntity<Void> updateBrandStatus(@RequestBody Blockchain blockchain) {
        if (Objects.isNull(blockchain.getStatus())) {
            throw new YamiShopBindException("状态不能为空");
        }
        if (Objects.isNull(blockchain.getId())) {
            throw new YamiShopBindException("链平台id不能为空");
        }
        List<Long> prodIds = blockchainService.updateBlockchainStatus(blockchain);
        productService.removeProductCacheByProdIds(prodIds);
        return ServerResponseEntity.success();
    }

    @GetMapping("/listSigningByShopId")
    @Operation(summary = "根据店铺id获取签约的链平台列表", description = "根据店铺id获取签约的链平台列表")
    @Parameters(value = {@Parameter(name = "shopId", description = "店铺id", required = true), @Parameter(name = "status", description = "状态 1:启用, 0:禁用")})
    public ServerResponseEntity<List<BlockchainShopVO>> listSigningByShopId(@RequestParam(name = "shopId") Long shopId, @RequestParam(name = "status", required = false) Integer status) {
        List<BlockchainShopVO> blockchainShopList = blockchainShopService.listSigningByShopId(shopId, status);
        return ServerResponseEntity.success(blockchainShopList);
    }

    @GetMapping("/pageSigningByShopId")
    @Operation(summary = "根据店铺id分页获取签约的链平台列表", description = "根据店铺id分页获取签约的链平台列表")
    public ServerResponseEntity<IPage<BlockchainShopVO>> pageSigningByShopId(PageParam<BlockchainShopVO> page, @ParameterObject BlockchainShopDTO blockchainShopDTO) {
        IPage<BlockchainShopVO> brandShopPage = blockchainShopService.pageSigningByShopId(page, blockchainShopDTO);
        return ServerResponseEntity.success(brandShopPage);
    }

    @PutMapping("/signing")
    @Operation(summary = "根据店铺id更新店铺下的签约链平台", description = "根据店铺id更新店铺下的签约链平台")
    @Parameter(name = "shopId", description = "店铺id")
    public ServerResponseEntity<Void> signingBrands(@RequestBody List<BlockchainShop> blockchainShopList, @RequestParam(name = "shopId") Long shopId) {
        blockchainShopService.signingBlockchain(blockchainShopList, shopId, true);
        return ServerResponseEntity.success();
    }

    @GetMapping("/checkBlockchainName")
    @Operation(summary = "检查链平台名称是否已存在", description = "检查链平台名称是否已存在")
    public ServerResponseEntity<Boolean> checkBlockchainName(@RequestParam(name = "name") String name, @RequestParam(name = "id") Long id) {
        long count;
        if (id != 0) {
            count = blockchainService.count(Wrappers.lambdaQuery(Blockchain.class).eq(Blockchain::getName, name).ne(Blockchain::getStatus, 0).ne(Blockchain::getId, id));
        } else {
            count = blockchainService.count(Wrappers.lambdaQuery(Blockchain.class).eq(Blockchain::getName, name).ne(Blockchain::getStatus, 0));
        }
        return ServerResponseEntity.success(count > 0);
    }

    @GetMapping("/checkBlockchainCode")
    @Operation(summary = "检查链平台编码是否已存在", description = "检查链平台编码是否已存在")
    public ServerResponseEntity<Boolean> checkBlockchainCode(@RequestParam(name = "code") String code, @RequestParam(name = "id") Long id) {
        long count;
        if (id != 0) {
            count = blockchainService.count(Wrappers.lambdaQuery(Blockchain.class).eq(Blockchain::getName, code).ne(Blockchain::getStatus, 0).ne(Blockchain::getId, id));
        } else {
            count = blockchainService.count(Wrappers.lambdaQuery(Blockchain.class).eq(Blockchain::getName, code).ne(Blockchain::getStatus, 0));
        }
        return ServerResponseEntity.success(count > 0);
    }

}
